package com.aaa.security;

import com.aaa.entity.ResultData;
import com.alibaba.fastjson.JSON;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AccessDeniedHandlerConfig implements AccessDeniedHandler {
    /**
     * 请求被拒绝：未认证
     * @param httpServletRequest 请求
     * @param httpServletResponse 响应
     * @param e 异常
     * @throws IOException
     * @throws ServletException
     */
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        PrintWriter writer = httpServletResponse.getWriter();
        // code
        int status = httpServletResponse.getStatus();
        String message = e.getMessage();
        ResultData resultData = new ResultData(status,message,null);
        writer.print(JSON.toJSON(new ResultData(status,message,e.toString())));
        writer.flush();
        writer.close();
    }
}
